package com.lagou.cofig;

import lagou.io.pojo.Configuration;
import lagou.io.pojo.MappedStagement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

public class XmlMapperBuild {
    private Configuration configuration;

    public XmlMapperBuild(Configuration configuration) {
        this.configuration = configuration;
    }

    public   void pase(InputStream inputStream) throws DocumentException {
        SAXReader saxReader = new SAXReader();
        Document read = saxReader.read(inputStream);
        Element rootElement = read.getRootElement();
        String namespace = rootElement.attributeValue("namespace");

        List<Element> list = rootElement.selectNodes("//select");

        List<Element> list2 = rootElement.selectNodes("//update");

        List<Element> list3 = rootElement.selectNodes("//delete");

        List<Element> list4 = rootElement.selectNodes("//insert");
       list.addAll(list2);
       list.addAll(list3);
       list.addAll(list4);
        for (Element o : list) {
            String id = o.attributeValue("id");
            String resultType = o.attributeValue("resultType");
            String paramterType = o.attributeValue("paramterType");
            String sql = o.getTextTrim();
            MappedStagement mappedStagement = new MappedStagement();
            mappedStagement.setId(id);
            mappedStagement.setParamterType(paramterType);
            mappedStagement.setResultType(resultType);
            mappedStagement.setSql(sql);
            configuration.getMappedStagement().put(namespace+"."+id,mappedStagement);
        }

    }
}
